package com.imooc.controller;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.gson.Gson;
import com.imooc.bo.DataDictionaryBO;
import com.imooc.bo.QueryDictItemsBO;
import com.imooc.pojo.DataDictionary;
import com.imooc.result.GraceJSONResult;
import com.imooc.service.DataDictionaryService;
import com.imooc.utils.GsonUtils;
import com.imooc.utils.PagedGridResult;
import com.imooc.vo.CompanyPointsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 数据字典表
 * </p>
 *
 * @author liansen
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/dataDict")
public class DataDictionaryController {

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //自定义线程池
    @Autowired
    private ThreadPoolExecutor executor;

    //新增或修改数据字典
    @PostMapping("/create")
    public GraceJSONResult createOrUpdateDataDictionary(@RequestBody @Validated DataDictionaryBO dataDictionaryBO){

        if(StringUtils.isBlank(dataDictionaryBO.getId())){
            //新增
            dataDictionaryService.createDataDictionary(dataDictionaryBO);
        }else {
            //更新
            dataDictionaryService.updateDataDictionary(dataDictionaryBO);
        }
        return GraceJSONResult.ok();
    }

    //分页查询数据字典
    @PostMapping("/list")
    public GraceJSONResult list(Integer page, Integer limit, String typeName, String itemValue){

        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        PagedGridResult result = dataDictionaryService.getDataByLimit(page, limit, typeName, itemValue);
        return GraceJSONResult.ok(result);
    }

    //查询数据字典回显
    @PostMapping("/item")
    public GraceJSONResult item(@RequestParam("dictId") String dictId){
        if(StringUtils.isBlank(dictId)){
            return GraceJSONResult.errorMsg("数据不存在");
        }
        DataDictionary dataDictionary = dataDictionaryService.getItem(dictId);
        return GraceJSONResult.ok(dataDictionary);
    }

    //修改数据字典
    @PostMapping("/modify")
    public GraceJSONResult modify(@RequestBody @Validated DataDictionaryBO dataDictionaryBO){
        if(StringUtils.isBlank(dataDictionaryBO.getId())){
            return GraceJSONResult.errorMsg("数据不存在");
        }
        dataDictionaryService.updateDataDictionary(dataDictionaryBO);
        return GraceJSONResult.ok();
    }

    //删除数据字典
    @PostMapping("/delete")
    public GraceJSONResult delete(@RequestParam("dictId") String dictId){
        if(StringUtils.isBlank(dictId)){
            return GraceJSONResult.error();
        }
        dataDictionaryService.delete(dictId);
        return GraceJSONResult.ok();
    }


//    @PostMapping("/app/getDataByCode")
//    public GraceJSONResult getDataByCode(@RequestParam("typeCode") String typeCode){
//        if(StringUtils.isBlank(typeCode)){
//            return GraceJSONResult.error();
//        }
//        List<DataDictionary> list = dataDictionaryService.getDataByCode(typeCode);
//        return GraceJSONResult.ok(list);
//    }

    @PostMapping("/app/getDataByCode")
    public GraceJSONResult getDataByCode(@RequestParam("typeCode") String typeCode){
        if(StringUtils.isBlank(typeCode)){
            return GraceJSONResult.error();
        }
        String redisJson = redisTemplate.opsForValue().get("dataDictionary" + ":" + typeCode);
        List<DataDictionary> dataDictionaries = new ArrayList<>();
        if(StringUtils.isNotBlank(redisJson)){
            //转为list集合
            dataDictionaries = GsonUtils.stringToList(redisJson, DataDictionary.class);
            return GraceJSONResult.ok(dataDictionaries);
        }else{
            dataDictionaries = dataDictionaryService.getDataByCode(typeCode);
            if(CollectionUtils.isNotEmpty(dataDictionaries)){
                String dataListByMysql = new Gson().toJson(dataDictionaries);
                redisTemplate.opsForValue().set("dataDictionary" + ":" + typeCode, dataListByMysql);
            }else {
                //防止缓存穿透, 如果用一个不存在的typeCode查,dataDictionaries为空,
                //就将这个不存在的typeCode放进redis，值设置为"[]",过期时间为10分钟;
                redisTemplate.opsForValue().set("dataDictionary" + ":" + typeCode, "[]", 10 * 60);
            }
        }
        return GraceJSONResult.ok(dataDictionaries);
    }


//    @PostMapping("/app/getItemsByKeys")
//    public GraceJSONResult getItemsByKeys(@RequestBody QueryDictItemsBO dictItemsBO){
//        String[] advantage = dictItemsBO.getAdvantage();
//        String[] benefits = dictItemsBO.getBenefits();
//        String[] bonus = dictItemsBO.getBonus();
//        String[] subsidy = dictItemsBO.getSubsidy();
//
//        List<DataDictionary> advantageList = dataDictionaryService.getData(advantage);
//        List<DataDictionary> benefitsList = dataDictionaryService.getData(benefits);
//        List<DataDictionary> bonusList = dataDictionaryService.getData(bonus);
//        List<DataDictionary> subsidyList = dataDictionaryService.getData(subsidy);
//
//        CompanyPointsVO companyPointsVO = new CompanyPointsVO();
//        companyPointsVO.setAdvantageList(advantageList);
//        companyPointsVO.setBenefitsList(benefitsList);
//        companyPointsVO.setBonusList(bonusList);
//        companyPointsVO.setSubsidyList(subsidyList);
//
//        return GraceJSONResult.ok(companyPointsVO);
//    }

    /**
     * 多线程优化上面的接口方法 (异步编排)
     */
    @PostMapping("/app/getItemsByKeys")
    public GraceJSONResult getItemsByKeys(@RequestBody QueryDictItemsBO dictItemsBO) throws Exception {

        CompanyPointsVO companyPointsVO = new CompanyPointsVO();

        CompletableFuture<List<DataDictionary>> advantageFuture = CompletableFuture.supplyAsync(() -> {
            String[] advantage = dictItemsBO.getAdvantage();
            List<DataDictionary> advantageList = dataDictionaryService.getData(advantage);
            companyPointsVO.setAdvantageList(advantageList);
            return advantageList;
        }, executor);

        CompletableFuture<List<DataDictionary>> benefitsFuture = CompletableFuture.supplyAsync(() -> {
            String[] benefits = dictItemsBO.getBenefits();
            List<DataDictionary> benefitsList = dataDictionaryService.getData(benefits);
            companyPointsVO.setBenefitsList(benefitsList);
            return benefitsList;
        }, executor);

        CompletableFuture<List<DataDictionary>> bonusFuture = CompletableFuture.supplyAsync(() -> {
            String[] bonus = dictItemsBO.getBonus();
            List<DataDictionary> bonusList = dataDictionaryService.getData(bonus);
            companyPointsVO.setBonusList(bonusList);
            return bonusList;
        });

        CompletableFuture<List<DataDictionary>> subsidyFuture = CompletableFuture.supplyAsync(() -> {
            String[] subsidy = dictItemsBO.getSubsidy();
            List<DataDictionary> subsidyList = dataDictionaryService.getData(subsidy);
            companyPointsVO.setSubsidyList(subsidyList);
            return subsidyList;
        });

        //alllOf: 等待所有任务完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(advantageFuture, benefitsFuture, bonusFuture, subsidyFuture);
        //如果不加allOf.get()这行代码，则后续代码是异步执行的, 这里得等所有任务完成后再返回
        allOf.get();
        return GraceJSONResult.ok(companyPointsVO);
    }

}

